package com.xqh.study.springtxjpa.service;

import com.xqh.study.springtxjpa.dao.CustomerRepository;
import com.xqh.study.springtxjpa.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @ClassName CustomerServiceInCode
 * @Description 编码方式实现 事务管理
 * @Author xuqianghui
 * @Date 2019/12/30 21:33
 * @Version 1.0
 */
@Service
public class CustomerServiceInCode {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    public Customer create(Customer customer){
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        definition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE);
        definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

        TransactionStatus status = platformTransactionManager.getTransaction(definition);
        try {
            customerRepository.save(customer);
            if(1 == 1){
                throw new RuntimeException("simulate error");
            }
            platformTransactionManager.commit(status);
            return customer;
        }catch (Exception e ){
            platformTransactionManager.rollback(status);
            throw e;
        }

    }
}
